package com.sian.anyun.web.controllers;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sian.security.web.model.Credential;
import com.sian.security.web.service.SecurityService;

@Controller
@RequestMapping("/file")
public class FileTransferController {
	private static final Logger logger = LoggerFactory.getLogger(FileTransferController.class);

	@Autowired
	SecurityService securityService;
	
	@ResponseBody
	@RequestMapping(value = "/upload/{file}", method = RequestMethod.POST)
	public String login(@PathVariable("file") String file, @RequestParam(value="path") String path, HttpServletRequest request)
	{
		logger.debug(file);
		
		Credential credential = securityService.getCredential();
		
		synchronized(credential)
		{
			try {
				// TODO:
				// Retrieval user space from credential
				// Change directory to path
				// Create output stream
				processData(request.getInputStream(), null);
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				throw new RuntimeException(e);
			}
		}
		
		return "";
	}
	
	protected void processData(ServletInputStream inputStream, OutputStream outputStream)
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		logger.debug("Upload file start.");
		byte[] buffer = new byte[1024];
		int bytesRead;
		try {
			while ((bytesRead = inputStream.read(buffer)) != -1) {
				baos.write(buffer, 0, bytesRead);
				// TODO: Write to storage.
			}
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e);
		}

		logger.debug("Upload file end.");
	}
}
